<template>
	<div>
		<van-search
			v-model="value"
			placeholder="请输入城市"
			style="margin-top: 40px; font-size: 18px"
		/>
		<van-index-bar
			style="margin-top: 10px; font-size: 18px"
			:index-list="computeCitylist"
			@select="select"
		>
			<div
				v-for="data in Citylist"
				:key="data.id"
				style="margin-top: 10px; background-color: #ccc"
			>
				<van-index-anchor :index="data.type" />
				<van-cell
					:title="item.name"
					v-for="(item, index) in data.list"
					:key="index"
					@click="handChangePage(item.name, item.cityId)"
				/>
			</div>
		</van-index-bar>
	</div>
</template>

<script>
import axios from 'axios'
import { Toast } from 'vant'
export default {
	data() {
		return {
			Citylist: [],
			value: '',
		}
	},
	methods: {
		//处理所有城市列表
		handCitys(cities) {
			// console.log(cities)
			//输入原始数据 输出目标数据
			//生成26个首字母
			let letterArr = []
			let newCity = []
			for (let code = 65; code < 91; code++) {
				// console.log(String.fromCharCode(code))
				letterArr.push(String.fromCharCode(code))
			}
			letterArr.forEach((letter) => {
				//循环26个字母比较原始数据首字母大写
				let list = cities.filter(
					(item) => item.pinyin.substring(0, 1).toUpperCase() === letter
				)
				if (list.length > 0) {
					newCity.push({
						type: letter,
						list: list,
					})
				}
			})
			return newCity
		},
		//点击索引列表轻提示
		select(index) {
			Toast(index)
		},
		handChangePage(name, id) {
			this.$store.commit('changeCityName', name)
			this.$store.commit('changeCityId', id)
			console.log(name, id)
			this.$router.back()
			//store 只是存在内存中的
			//store 持久化存储
		},
	},
	computed: {
		//解决自定义列表的数据
		computeCitylist() {
			return this.Citylist.map((item) => item.type)
		},
	},
	mounted() {
		axios({
			url: '/api/gateway?k=6326852',
			methods: 'get',
			headers: {
				'X-Client-Info':
					'{"a":"3000","ch":"1002","v":"5.2.1","e":"1676514945111647674859521"}',
				'X-Host': 'mall.film-ticket.city.list',
			},
		}).then((res) => {
			// console.log(res.data.data.cities)

			this.Citylist = this.handCitys(res.data.data.cities)
		})
	},
}
</script>

<style scoped>
.van-search {
}
</style>
